package com.example.healthy_station_flutter

import android.Manifest
import android.app.PendingIntent
import android.content.Intent
import android.content.IntentFilter
import android.hardware.usb.UsbManager
import android.os.Bundle
import android.util.Log
import com.example.healthy_station_flutter.receiver.time.TimeCallback
import com.example.healthy_station_flutter.receiver.time.TimeReceiver
import com.example.healthy_station_flutter.service.UsbPermissionCallback
import com.example.healthy_station_flutter.service.UsbPermissionReceiver
import com.example.healthy_station_flutter.utils.LOGIN_CHANNEL
import com.example.healthy_station_flutter.utils.LOGIN_CHANNEL_ACCOUNT
import com.example.healthy_station_flutter.utils.LOGIN_CHANNEL_ELECTRIC
import com.example.healthy_station_flutter.utils.LOGIN_CHANNEL_FACE
import com.example.healthy_station_flutter.utils.LOGIN_CHANNEL_IDENTITY
import com.example.healthy_station_flutter.utils.LOGIN_CHANNEL_SOCIAL
import com.example.healthy_station_flutter.utils.PermissionUtil
import com.example.healthy_station_flutter.utils.TIME_CHANNEL
import com.qdsg.modulesihealsdk.SihealSdkUtils
import com.qdsg.modulesihealsdk.deCard.InitDeviceCallback
import com.qdsg.modulesihealsdk.deCard.ReadCardUtilsCallback
import com.qdsg.modulesihealsdk.entity.IdCardBean
import com.qdsg.modulesihealsdk.entity.SocialSecurityCardBean
import io.flutter.embedding.android.FlutterActivity
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodChannel
import java.util.LinkedList

class MainActivity: FlutterActivity(), UsbPermissionCallback, TimeCallback.TimeInterface {

    companion object{
        var timeInterface: TimeCallback.TimeInterface? = null
    }
    var eventSink: EventChannel.EventSink? = null
    var eventChannel: EventChannel? = null


    //首先定义请求变量
    private var permissionList = LinkedList<String>().apply {
        add(Manifest.permission.ACCESS_FINE_LOCATION)
        add(Manifest.permission.ACCESS_COARSE_LOCATION)
        add(Manifest.permission.RECORD_AUDIO)
        add(Manifest.permission.CAMERA)
        add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
        add(Manifest.permission.READ_EXTERNAL_STORAGE)
    }

    val REQUEST_CODE = 1


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        timeInterface = this
        SihealSdkUtils.initTTS()
        PermissionUtil.instance.requestPermissions(this,permissionList,REQUEST_CODE)
        setMethodChannel()
        lifecycle.addObserver(TimeReceiver(this))

        eventChannel  = EventChannel(flutterEngine?.dartExecutor?.binaryMessenger,TIME_CHANNEL)
        eventChannel!!.setStreamHandler(object : EventChannel.StreamHandler {
            override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
                eventSink = events
            }

            override fun onCancel(arguments: Any?) {
            }

        })


    }

    private fun setMethodChannel(){
        val methodChannel = MethodChannel(flutterEngine!!.dartExecutor.binaryMessenger, LOGIN_CHANNEL)
        methodChannel.setMethodCallHandler { methodCall, result ->
            if (methodCall.method != null) {
                //方法被Flutter调用
                Log.d("__arguments-1","${methodCall.arguments}")
                when(methodCall.arguments){
                    LOGIN_CHANNEL_IDENTITY -> {
                        Log.d("__arguments-2","${methodCall.arguments}")
                        readIdCard(result)
                    }
                    LOGIN_CHANNEL_SOCIAL -> { readSocialSecurityCard(result) }
                    LOGIN_CHANNEL_FACE -> { readIdCard(result) }
                    LOGIN_CHANNEL_ELECTRIC -> { readIdCard(result) }
                    LOGIN_CHANNEL_ACCOUNT -> { readIdCard(result) }
                }
            } else {
                result.notImplemented()
            }
        }
    }


    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_CODE){
            if (grantResults.size == 6){
                tryGetUsbPermission()
            }
        }
    }


    /**
     * 获得 usb 权限
     */
    private fun tryGetUsbPermission() {
        val mUsbManager = getSystemService(USB_SERVICE) as UsbManager
        val usbPermissionActionReceiver = UsbPermissionReceiver(this)
        val filter = IntentFilter(UsbPermissionReceiver.ACTION_USB_PERMISSION)
        registerReceiver(usbPermissionActionReceiver, filter)
        val mPermissionIntent =
            PendingIntent.getBroadcast(this, 0, Intent(UsbPermissionReceiver.ACTION_USB_PERMISSION), 0)

        //here do emulation to ask all connected usb device for permission
        for (usbDevice in mUsbManager.deviceList.values) {
            if (usbDevice.vendorId == 9595 && usbDevice.productId == 12305 ||
                usbDevice.vendorId == 9595 && usbDevice.productId == 12306 ||
                usbDevice.vendorId == 9595 && usbDevice.productId == 12304 ||
                usbDevice.vendorId == 9595 && usbDevice.productId == 40961 ||
                usbDevice.vendorId == 9595 && usbDevice.productId == 40963 ||
                usbDevice.vendorId == 1137 && usbDevice.productId == 28674 ||
                usbDevice.vendorId == 1137 && usbDevice.productId == 28675 ||
                usbDevice.vendorId == 1137 && usbDevice.productId == 41234 ||
                usbDevice.vendorId == 1137 && usbDevice.productId == 41299 ||
                usbDevice.vendorId == 1137 && usbDevice.productId == 41267 ||
                usbDevice.vendorId == 9595 && usbDevice.productId == 12337 ||
                usbDevice.vendorId == 1137 && usbDevice.productId == 41253) {
                if (mUsbManager.hasPermission(usbDevice)) {
                    //已经拥有权限
                    initUsbDevice()
                } else {
                    mUsbManager.requestPermission(usbDevice, mPermissionIntent)
                }
            }
        }
    }

    fun initUsbDevice(){
        SihealSdkUtils.initDevice(this, object : InitDeviceCallback {
            override fun success() {}

            override fun failed() {}

        })
    }

    override fun result() {
        initUsbDevice()
    }


    /**
     * 身份证登录
     */
    fun readIdCard(result: MethodChannel.Result) {
        //todo wjf 测试
        if (BuildConfig.DEBUG){
            val idCardBean = IdCardBean()
            idCardBean.name = "吴剑锋"
            idCardBean.gender = "男"
            idCardBean.group = "汉"
            idCardBean.born = "19960729"
            idCardBean.address = "address"
            idCardBean.idNumber = "350624199607290513"
            idCardBean.startDate = "20231223"
            idCardBean.endDate = "20431223"
            idCardBean.issueAuthority = "诏安县公安局"
            idCardBean.keyString = ""
            result.success(idCardBean.toString())
//            result.success("err")
            return
        }

        SihealSdkUtils.readIdCard(this, object : ReadCardUtilsCallback {
            override fun idCardData(idCardBean: IdCardBean) {
                result.success(idCardBean)
            }

            override fun socialSecurityCardData(socialSecurityCardBean: SocialSecurityCardBean?) {}
            override fun nullCard() {
                result.success("")

            }

            override fun errMsg(errMsg: String?) {
                result.success("err:${errMsg}")
            }
        })
    }


    /**
     * 社保卡登录
     */
    fun readSocialSecurityCard(result: MethodChannel.Result) {

        //todo wjf 测试
        if (BuildConfig.DEBUG){
            val socialSecurityCardBean = SocialSecurityCardBean()
            socialSecurityCardBean.socialSecurityNumber = "350624199607290513"
            socialSecurityCardBean.name = "吴剑锋"
            socialSecurityCardBean.gender = "男"
            socialSecurityCardBean.group = "汉族"
            socialSecurityCardBean.bornNum = ""
            socialSecurityCardBean.born = "19960729"
            socialSecurityCardBean.cardIdNum = "330100D156000005007CC3E4673B7473"
            socialSecurityCardBean.cardType = "3"
            socialSecurityCardBean.cardVersion = "1.00"
            socialSecurityCardBean.initCode = "915600000233010033010015"
            socialSecurityCardBean.cardStartDate = "20151110"
            socialSecurityCardBean.cardEndDate = "20251110"
            socialSecurityCardBean.cardNum = "W35252428"
            socialSecurityCardBean.socialCardKxx = ""
            result.success(socialSecurityCardBean.toString())
            return
        }
        SihealSdkUtils.readSocialSecurityCard(this, object : ReadCardUtilsCallback {
            override fun idCardData(idCardBean: IdCardBean?) {}

            override fun socialSecurityCardData(socialSecurityCardBean: SocialSecurityCardBean) {
            }

            override fun nullCard() {
            }

            override fun errMsg(errMsg: String?) {
            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        timeInterface = null
        eventSink = null
        eventChannel = null
    }
    override fun updateTime(time: String) {
        eventSink?.success(time)

    }
}
